package com.dcc.inventory.interceptor;


import com.dcc.inventory.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author admin
 */
public class LoginInterceptor implements HandlerInterceptor {
    public static String AUTH = null;

    /**
     * @author admin
     * 在 @controller 视图渲染之后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) {

    }

    /**
     * @author admin
     * 在 @Controller方法执行之后，在视图渲染之前执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse arg1, Object arg2, ModelAndView arg3) {
        // 在处理过程中，执行拦截

    }

    /**
     * @author admin
     * 在 @controller 方法之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        User index_user = (User) session.getAttribute("index_user");
        if(user != null) {
            return true;
        }
        if(index_user != null ) {
            String authorization = request.getHeader("Authorization");
            String auth = authorization.substring(7);
            String auth1 = (String) session.getAttribute("auth");
            if (auth1.equals(auth)) {
                return true;
            }
        }
        if(user == null){
//            拦截后进入登录页面
            response.sendRedirect(request.getContextPath() + "/inventory/login.html");
            return false;
        }
        return false;
    }

}
